package com.expect.admin.busmanagement.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.expect.admin.busmanagement.service.BusService;
import com.expect.admin.busmanagement.service.vo.BusVo;
import com.expect.admin.config.Settings;
import com.expect.admin.service.AttachmentService;
import com.expect.admin.service.LcService;
import com.expect.admin.service.LcrzbService;
import com.expect.admin.service.RoleJdgxbGxbService;
import com.expect.admin.service.RoleService;
import com.expect.admin.service.UserService;
import com.expect.admin.service.vo.LcrzbVo;
import com.expect.admin.service.vo.RoleJdgxbGxbVo;
import com.expect.admin.service.vo.RoleVo;
import com.expect.admin.service.vo.UserVo;
import com.expect.admin.service.vo.component.FileResultVo;
import com.expect.admin.service.vo.component.ResultVo;
import com.expect.admin.utils.DateUtil;
import com.expect.admin.utils.JsonResult;
import com.expect.admin.utils.MyResponseBuilder;
import com.expect.admin.utils.StringUtil;

@Controller
@RequestMapping(value = "/admin/busmanagement")
public class BusController {
	/**
	 * slf4j简单日志门面
	 */
	private final Logger log = LoggerFactory.getLogger(BusController.class);

	@Autowired
	private BusService busService;
	@Autowired
	private LcrzbService lcrzbService;
	@Autowired
	private LcService lcService;
	@Autowired
	private UserService userService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private Settings settings;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleJdgxbGxbService roleJdgxbGxbService;

	private final String viewName = "admin/busManagement/";

	/**
	 * 维保申请界面
	 */
	@RequestMapping(value = "/addManagement", method = RequestMethod.GET)
	public ModelAndView addManagement() {
		BusVo busVo = new BusVo();
		UserVo userVo = userService.getLoginUser();
		busVo.setUserName(userVo.getFullName());
		ModelAndView mv = new ModelAndView(viewName + "b_apply");
		mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 申请记录界面
	 */
	@GetMapping(value = "/applicationRecord")
	public ModelAndView applicationRecord(@RequestParam(name = "state", required = false) String state) {
		if (StringUtil.isBlank(state))
			state = "wtj";
		ModelAndView mv = new ModelAndView(viewName + "b_apply_record");
		UserVo userVo = userService.getLoginUser();
		RoleJdgxbGxbVo condition = roleJdgxbGxbService.getWjzt("application", "wb");
		mv.addObject("busVoList",busService.getBusByUserIdAndCondition(userVo.getId(),condition.getJdId(),state));
		return mv;
	}

	/**
	 * 申请记录详情（可编辑）
	 */
	@RequestMapping("/applicationRecordDetailE")
	public ModelAndView applicationRecordDetailE(@RequestParam(name = "id", required = true) String busId) {
		ModelAndView mv = new ModelAndView(viewName + "b_apply_recordDetailE");
		BusVo busVo = busService.getBusById(busId);
		mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 申请记录详情（不可编辑）
	 */
	@RequestMapping("/applicationRecordDetailNE")
	public ModelAndView applicationRecordDetailNE(@RequestParam(name = "id", required = true) String busId) {
		ModelAndView mv = new ModelAndView(viewName + "b_apply_recordDetailNE");
		BusVo busVo = busService.getBusById(busId);
		mv.addObject("busVo", busVo);
		return mv;
	}

	/**
	 * 保存和提交申请
	 * saveWay的required=true【【【【暂时改成false调试】改成true提交显示申请失败，缺少当前节点】】】
	 * @param busVo
	 * @param saveWay
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/saveApplication", method = RequestMethod.POST)
	public void saveApplication(BusVo busVo, @RequestParam(name = "saveWay", required = true) String saveWay,
			@RequestParam(name = "fileId", required = false) String[] attachmentId, HttpServletResponse response)
			throws IOException {
		if (!busCheck(busVo, response))
			return;
		String message = StringUtil.equals(saveWay, "submit") ? "维保申请" : "申请保存";
		try {
			busService.newApplicationSave(busVo, saveWay, attachmentId);
		} catch (Exception e) {
			log.error("保存申请报错", e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, message + "失败！").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, message + "成功！").build());
	}

	/**
	 * 申请不能为空
	 * 
	 * @param busVo
	 * @param response
	 * @return 满足要求返回true，否则返回false
	 * @throws IOException
	 */
	private boolean busCheck(BusVo busVo, HttpServletResponse response) throws IOException {
		if (busVo == null) {
			log.error("试图保存空的申请");
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "申请失败，申请内容为空！").build());
			return false;
		}
		return true;
	}

	/**
	 * 更新申请内容
	 * 
	 * @param busVo
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
    @RequestMapping(value = "/updateApplication",method = RequestMethod.POST)
	public void updateApplication(BusVo busVo,
	        @RequestParam(name = "fileId", required = false) String[] attachmentId,
	        HttpServletResponse response) throws IOException {
	    try{ 
	    	busService.updateApplication(busVo,attachmentId);
	    }catch(Exception e){ 
	    	log.error("更新申请内容报错", e);
	        MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "更新申请内容失败！").build());
	    }
	    MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(true, "更新申请内容成功！").build()); 
	}
	 
	/**
	 * 删除已提交的申请（软删除）
	 * 
	 * @param response
	 * @param id
	 * @throws IOException
	 */
	@PostMapping("/deleteApplication") 
	public void deleteApplication(HttpServletResponse response,
	                              @RequestParam(name = "id",required = true)String id) throws IOException{
		try{ 
			busService.deleteApplication(id);
	    }catch(Exception e){ 
	    	log.error("删除申请失败未找到id为" + id + "的申请", e);
	        MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "未找到要删除的申请！").build());
	    }
	    MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "删除申请成功！").build()); 
	}
	 
	/**
	 * 申请附件上传
	 * 
	 * @param files
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadBusAttachment", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo upload(MultipartFile files, HttpServletRequest request) {
		String path = settings.getAttachmentPath();
//		path = Base64Util.decode(path);//不知什么影响
		FileResultVo frv = attachmentService.save(files, path);
		return frv;
	}

	/**
	 * 已保存的申请的提交
	 * 
	 * @param id
	 * @param attachmentId
	 * @param response
	 * @throws IOException
	 */
	@PostMapping("/submitWtj") 
	public void submitWtj(String id,
			@RequestParam(name = "fileId",required = false) String[] attachmentId,
	        HttpServletResponse response) throws IOException{ 
		
		try{
			BusVo busVo = busService.getBusById(id); 
			if(busVo == null){ 
				MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "未找到该申请").build());
	            return; 
	        } 
            String nextCondition = lcService.getNextCondition(busVo.getLcbs(), busVo.getApplicationStatement());
            busVo.setApplicationStatement(nextCondition);
            busService.updateApplication(busVo, attachmentId);
            busService.addXzLcrz(busVo.getId(),busVo.getApplicationClassify(),nextCondition);
        }catch(Exception e){
        	log.error("已保存的申请提交时报错", e);
	        MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "申请提交失败，请重试！").build());
	    } 
		MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(true, "申请提交成功！").build()); 
	}
	 
	/**
	 * 已保存未提交的申请的删除
	 * 
	 * @param id
	 * @param response
	 * @throws IOException
	 */
	@PostMapping("/deleteWtj") 
	public void deleteWtj(String id,HttpServletResponse response) throws IOException{ 
		try{
			if(StringUtil.isBlank(id)){ 
				MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "申请提交失败，要删除的申请id为空").build()); 
			    return; 
			}
			busService.delete(id); 
		}catch(Exception e){ 
			log.error("已保存申请提交时报错", e);
			MyResponseBuilder.writeJsonResponse(response,JsonResult.useDefault(false, "申请删除失败！").build()); 
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true,"申请删除成功！").build()); 
	}
	
	/**
	 * 维保审批查看详情
	 * @param busNo
	 * @return
	 */
	@PostMapping(value = "/busApproveDetail")
	public ModelAndView busApproveDetail(@RequestParam(name = "id", required = true)String busId){
		ModelAndView mv = new ModelAndView(viewName + "b_approveDetail");
		BusVo busVo = busService.getBusById(busId);
		mv.addObject("busVo", busVo);
		return mv;
	}
	
	/**
	 * 申请记录tab 维保申请的审批tab
	 * @param state
	 * @param bz
	 * @param response
	 * @throws IOException
	 */
	@GetMapping(value = "/applicationRecordTab")
	public void applicationRecordTab(@RequestParam(name = "state",required = false)String state,
			                         @RequestParam(name = "bz",required = false)String bz,
			HttpServletResponse response) throws IOException{
		if(StringUtil.isBlank(state)){
			state = "wtj";
		}
		List<BusVo> busVoList = new ArrayList<BusVo>();
		try{
			UserVo userVo = userService.getLoginUser();
			RoleJdgxbGxbVo condition = roleJdgxbGxbService.getWjzt(bz, "wb");
			//申请记录的已审批
			if(StringUtil.equals(bz, "application") && StringUtil.equals(state, "ysp")){
				busVoList = busService.getApplicationRecordYspList(userVo.getId());
				MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "获取申请记录成功", busVoList).build());
				return;
			}
	
			//申请记录的待审批
			if(StringUtil.equals(bz, "application") && StringUtil.equals(state, "dsp")){
				busVoList = busService.getApplicationRecordWspList(userVo.getId(), condition.getJdId());
				MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "获取申请记录成功", busVoList).build());
				return;
			}
			
			//已回填
			if(StringUtil.equals(state, "yht")){
				busVoList = busService.getBusByUserIdAndCondition(userVo.getId(), "T", state);
			}else{
				busVoList = busService.getBusByUserIdAndCondition(userVo.getId(), condition.getJdId(), state);
			}
		}catch(Exception e){
//			e.printStackTrace();
			log.error("获取申请记录错误" + state, e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "获取申请记录出错").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "获取申请记录成功", busVoList).build());
	}
	
	/**
	 * 维保审批
	 */
	@GetMapping(value = "/busApprove")
	public ModelAndView busApprove(@RequestParam(name = "state",required = false)String state){
		UserVo userVo = userService.getLoginUser();
		if(StringUtil.isBlank(state)){
			state = "dsp";
		}
		ModelAndView mv = new ModelAndView(viewName + "b_approve");
		RoleJdgxbGxbVo condition = roleJdgxbGxbService.getWjzt("approve", "wb");
		if(condition == null){
			return mv;
		}
		RoleVo roleVo = roleService.getRoleById(condition.getRoleId());
		String roleName = roleVo.getName();
		mv.addObject("xsth", sfxsTab(roleName,"yth"));
		mv.addObject("roleName", roleVo.getName());
		System.out.println(roleVo.getName());
		mv.addObject("busVoList", busService.getBusByUserIdAndCondition(userVo.getId(), condition.getJdId(), state));
		return mv;
	}

	/**
	 * 判断某些tab是否显示/部门负责人
	 * “”中原为文员
	 * @param term 判断条件
	 * @param tabName 要判断的tab
	 * @return true tab显示<br>
	 * false tab不显示
	 */
	private boolean sfxsTab(String term, String tabName) {
		// 已退回tab 用户角色为
		if(StringUtil.equals(tabName, "yth")){
			return !StringUtil.isBlank(term) && (term.endsWith("驾驶员") || StringUtil.equals(term, "主管"));//"",""角色分配需要改
		}
		return false;
	}
	
	/**
	 * 获取编号回填
	 */
	@RequestMapping("/getBhhtList")
	public ModelAndView getBhhtList(@RequestParam(name = "state", required = false)String state){
		ModelAndView mv = new ModelAndView(viewName + "b_backfill");
		if(StringUtil.isBlank(state)){
			state = "dht";
		}
		UserVo userVo = userService.getLoginUser();
//		FunctionJdgxbGxbVo functionJdgxbGxbVo = functionJdgxbGxbService.getByFunctionName("编号回填");
		mv.addObject("busVoList", busService.getBusByUserIdAndCondition(userVo.getId(), "Y", state));
		return mv;
	}
	
	/**
	 * 编号回填详情
	 */
	@PostMapping("/bhhtDetail")
	public ModelAndView bhhtDetail(@RequestParam(name = "id", required = true)String busId){
		ModelAndView mv = new ModelAndView(viewName + "b_backfillDetail");
		BusVo busVo = busService.getBusById(busId);
		mv.addObject("busVo", busVo);
		return mv;
	}
	
	/**
	 * 流程审批
	 * @param response
	 * @param cljg
	 * @param message
	 * @param clnrid
	 * @throws IOException
	 */
	@RequestMapping(value = "/addLcrz", method = RequestMethod.POST)
	public void addLcrz(HttpServletResponse response,
			@RequestParam(name = "cljg", required = true)String cljg,
			@RequestParam(name = "yj", required = false)String message,
			@RequestParam(name = "id", required = true)String clnrid
			)throws IOException{
		/**
		 * 插入流程日志
		 * 判断审核是否通过 ，如果通过更新文件状态到下一个状态
		 * 如果不通过更新文件状态到退回状态，修改流程日志表中的审批记录以后不再显示退回状态之后的审批记录
		 */
		if(message == null){
			message = "";
		}
		try{
			busService.saveBusLcrz(cljg,message,clnrid,"wb");
		}catch(Exception e){
			log.error("维保审核失败",e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false,"维保审核失败！").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true,"维保审核成功！").build());
	}
	
	/**
	 * 车辆编号回填
	 * 1.车辆编号号不能超过20位数且唯一
	 * 2.车辆编号回填后修改申请状态为T（已回填）
	 * 3.增加车辆编号回填流程日志
	 * @param response
	 * @param bh
	 * @param id
	 * @throws IOException
	 */
	@RequestMapping(value = "/bhht", method = RequestMethod.POST)
	public void busBhht(HttpServletResponse response,
			@RequestParam(name = "bh",required = true)String bh,
			@RequestParam(name = "id",required = true)String id) throws IOException{
		if(bh.length() > 20){
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "车辆编号过长，不能超过20个字符！").build());
			return;
		}
		if(!busService.isBusBhUnique(bh)){
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "车辆编号已存在，请重新填写！"));
			return;
		}
		BusVo busVo = busService.getBusById(id);
		busVo.setBh(bh);
		busVo.setApplicationStatement("T");
		busService.updateApplication(busVo, null);
		String lcrzId = lcrzbService.save(new LcrzbVo("车辆编号回填",bh), id, busVo.getApplicationClassify(), "T");
		busService.bindBusWithLcrz(busVo.getId(), lcrzId);
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "车辆编号回填成功！").build());
	}
	
	/**
	 * 申请查询
	 */
	@GetMapping("busSearch")
	public ModelAndView busSearch(){
		ModelAndView mv = new ModelAndView(viewName + "b_find");
		return mv;
	}
	
	/**
	 * 
	 * @param response
	 * @param busNo 车牌号
	 * @param busBh 车辆编号
	 * @param startTime 开始时间（搜索的时间段，以申请时间为准）
	 * @param endTime 结束时间
	 * @param applicationStatement 申请状态（0 ：全部， 1：待审批， 2 ：已审批， 3 ： 已回填）
	 * @param userName 驾驶员（申请人）
	 * @throws IOException
	 */
	@PostMapping("/searchBus")
	public void busSearchResult(HttpServletResponse response,
			@RequestParam(name = "busNo", required = false)String busNo,
			@RequestParam(name = "busBh", required = false)String busBh,
			@RequestParam(name = "startTime", required = false)String startTime,
			@RequestParam(name = "endTime", required = false)String endTime,
			@RequestParam(name = "applicationStatement", required = false)String applicationStatement,
			@RequestParam(name = "userName", required = false)String userName) throws IOException{
		Date start = null,end = null;
		List<BusVo> busVoList = null;
		try{
			if(!StringUtil.isBlank(startTime)){
				start = DateUtil.parse(startTime, DateUtil.zbFormat);
			}
			if(!StringUtil.isBlank(endTime)){
				end = DateUtil.parse(endTime,DateUtil.zbFormat);
			}
			busVoList = busService.searchBus(busNo, busBh, start, end, applicationStatement, userName, "");
		}catch(Exception e){
			log.error("申请查询失败",e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "搜索申请失败！").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "",busVoList).build());
	}
	
	/**
	 * 个人使用的部分申请查询
	 * 只能查询与当前登录用户相关（当前用户参与了维保申请的申请或者审批）的申请
	 * @param response
	 * @param busNo 车牌号
	 * @param busBh 车辆编号
	 * @param startTime 开始时间（搜索的时间段，以申请时间为准）
	 * @param endTime 结束时间
	 * @param applicationStatement 合同状态（0 ：全部， 1：待审批， 2 ：已审批， 3 ： 已回填）
	 * @param userName 申请人/驾驶员
	 * @throws IOException
	 */
	@PostMapping("/searchBusOfUser")
	public void busSearchResultOfUser(HttpServletResponse response,
			@RequestParam(name = "busNo", required = false)String busNo,
			@RequestParam(name = "busBh", required = false)String busBh,
			@RequestParam(name = "startTime", required = false)String startTime,
			@RequestParam(name = "endTime", required = false)String endTime,
			@RequestParam(name = "applicationStatement", required = false)String applicationStatement,
			@RequestParam(name = "userName", required = false)String userName) throws IOException{
		UserVo userVo = userService.getLoginUser();//获取当前登陆用户
		Date start = null,end = null;
		List<BusVo> busVoList = null;
		try{
			if(!StringUtil.isBlank(startTime)){
				start = DateUtil.parse(startTime, DateUtil.zbFormat);
			}
			if(!StringUtil.isBlank(endTime)){
				end = DateUtil.parse(endTime, DateUtil.zbFormat);
			}
			busVoList = busService.searchBus(busNo, busBh, start, end, applicationStatement, userName, userVo.getId());
		}catch(Exception e){
			log.error("申请查询失败",e);
			MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(false, "搜索申请失败！").build());
		}
		MyResponseBuilder.writeJsonResponse(response, JsonResult.useDefault(true, "",busVoList).build());
	}
	
	/**
	 * 搜索页面查看详情
	 * @param id
	 * @param response
	 * @return
	 */
	@PostMapping("/ssxq")
	public ModelAndView getSsxq(String id, HttpServletResponse response){
		ModelAndView mv = new ModelAndView(viewName + "b_findDetail");
		BusVo busVo = busService.getBusById(id);
		mv.addObject("busVo", busVo);
		return mv;
	}
}
